/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Col,
  Row,
  Button,
  Input,
  message,
  List,
  Pagination,
  Badge,
  Divider,
  Dropdown,
  Menu,
  Select,
} from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import TextOverFlow from '../../components/TextOverFlow';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
@connect(({ definition, loading }) => ({
  definition,
  loading: loading.effects['definition/fetchList'],
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      PD_CATE: [],
      PD_BILL_FREQ: [],
    };
    this.formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 17,
      },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['PD_CATE', 'PD_BILL_FREQ'],
    }).then(data => {
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      if (data.PD_CATE.length) {
        data.PD_CATE.map(item => {
          switch (item.itemCode) {
            case '1':
              return (item.pdCateName = '社保');
            case '2':
              return (item.pdCateName = '公积金');
            case '3':
              return (item.pdCateName = '福利');
            case '4':
              return (item.pdCateName = '工资');
            case '5':
              return (item.pdCateName = '临时费用');
            case '6':
              return (item.pdCateName = '代报税');
            case '7':
              return (item.pdCateName = '其他产品');
            default:
              return (item.pdCateName = '');
          }
        });
      }
      if (data.PD_BILL_FREQ.length) {
        data.PD_BILL_FREQ.map(item => {
          switch (item.itemCode) {
            case '1':
              return (item.billFreqName = '自然日');
            case '2':
              return (item.billFreqName = '自然月');
            case '3':
              return (item.billFreqName = '次');
            default:
              return (item.billFreqName = '');
          }
        });
      }
      this.setState({
        PD_CATE: data.PD_CATE,
        PD_BILL_FREQ: data.PD_BILL_FREQ.sort(sortNumber),
      });
    });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      definition: {
        pageData: { pagination },
        formFieldsValue,
      },
      dispatch,
      location,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'definition/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, definition, dispatch } = this.props;
    if (definition && definition.valuesArr) {
      form.validateFieldsAndScroll([...definition.valuesArr], (err, values) => {
        if (!err) {
          dispatch({
            type: 'definition/updateModelData',
            payload: {
              formFieldsValue: values,
            },
          });
          this.searchList(this.processFormData(values));
        }
      });
    }
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    const pagerArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pagerArg,
    };

    dispatch({
      type: 'definition/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'definition/fetchList',
      payload: {
        ...values,
      },
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'pdName' || key === 'pdInfo') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] =
          tempFieldsValue[key].key === undefined ? '' : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? '' : tempFieldsValue[key];
      }
    });
    return formFieldsValue;
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'definition/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 启用/停用状态
  ableStatus = (pdId, flag) => {
    const {
      dispatch,
      definition: { pageData, formFieldsValue },
    } = this.props;
    const openFlag = flag === 1 ? 2 : 1;
    dispatch({
      type: 'definition/ableStatus',
      payload: { pdId, openFlag },
    }).then(res => {
      if (res.success) {
        message.success(`${res.message || flag === 1 ? '停用成功！' : '启用成功！'}`);
        this.searchList(
          this.processFormData(formFieldsValue),
          pageData.pagination.current,
          pageData.pagination.pageSize
        );
      } else {
        message.warning(res.message || '服务器端错误');
      }
    });
  };

  // 修改
  update = id => {
    router.push(`/productmanage/definition/update?pdId=${id}`);
  };

  // 切换表格展开收起
  toggleForm = () => {
    const {
      dispatch,
      definition: { expandForm },
    } = this.props;
    dispatch({
      type: 'definition/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      definition,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="产品名称:" {...this.formItemLayout}>
              {getFieldDecorator('pdName', {
                initialValue:
                  definition && definition.formFieldsValue && definition.formFieldsValue.pdName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="产品描述：" {...this.formItemLayout}>
              {getFieldDecorator('pdInfo', {
                initialValue:
                  definition && definition.formFieldsValue && definition.formFieldsValue.pdInfo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      definition,
    } = this.props;
    const { PD_CATE } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="产品名称:" {...this.formItemLayout}>
              {getFieldDecorator('pdName', {
                initialValue:
                  definition && definition.formFieldsValue && definition.formFieldsValue.pdName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="产品描述：" {...this.formItemLayout}>
              {getFieldDecorator('pdInfo', {
                initialValue:
                  definition && definition.formFieldsValue && definition.formFieldsValue.pdInfo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="分类" {...this.formItemLayout}>
              {getFieldDecorator('pdCate', {
                rules: [{ required: false, message: '请选择' }],
                initialValue:
                  definition && definition.formFieldsValue && definition.formFieldsValue.pdCate,
              })(
                <HOCSelect
                  placeholder="请选择"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {PD_CATE.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { definition } = this.props;
    if (definition) {
      return definition.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }
  }

  render() {
    const { loading, definition } = this.props;
    const { PD_CATE, PD_BILL_FREQ } = this.state;
    const pagination = {
      style: {
        width: '100%',
        textAlign: 'right',
        padding: '20px 0 20px 0',
        borderTop: '1px solid #e8e8e8',
      },
      defaultCurrent:
        definition &&
        definition.pageData &&
        definition.pageData.pagination &&
        definition.pageData.pagination.current, // 默认当前页
      defaultPageSize:
        definition &&
        definition.pageData &&
        definition.pageData.pagination &&
        definition.pageData.pagination.pageSize, // 默认单页条数
      current:
        definition &&
        definition.pageData &&
        definition.pageData.pagination &&
        definition.pageData.pagination.current, // 当前页
      pageSize:
        definition &&
        definition.pageData &&
        definition.pageData.pagination &&
        definition.pageData.pagination.pageSize, // 单页条数
      total:
        definition &&
        definition.pageData &&
        definition.pageData.pagination &&
        definition.pageData.pagination.total, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.searchList(
          this.processFormData(definition && definition.formFieldsValue),
          page,
          pageSize
        );
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.searchList(
          this.processFormData(definition && definition.formFieldsValue),
          current,
          size
        );
      },
      showTotal: total => {
        if (
          definition &&
          definition.pageData &&
          definition.pageData.pagination &&
          definition.pageData.pagination.pageSize
        ) {
          const totalPage =
            total < definition.pageData.pagination.pageSize
              ? 1
              : Math.ceil(total / definition.pageData.pagination.pageSize);
          return `共 ${total} 条记录 第 ${pagination.current} / ${totalPage}页`;
        }
      },
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Authorized authority="mgr:baseProductInfo:insert" noMatch={null}>
            <Button
              type="primary"
              style={{ marginBottom: 8 }}
              icon={<PlusOutlined />}
              onClick={() => router.push('/productmanage/definition/add')}
            >
              新增
            </Button>
          </Authorized>
          <List
            loading={loading}
            dataSource={definition && definition.pageData && definition.pageData.list}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  title={<span style={{ fontWeight: 'bold' }}>{item.pdName}</span>}
                  description={<TextOverFlow text={item.pdInfo} lineClampNum="1" />}
                />
                {PD_BILL_FREQ.map(values => {
                  if (Number(values.itemCode) === item.billFreq) {
                    return <List.Item.Meta title="计费频率" description={values.billFreqName} />;
                  }
                })}
                <List.Item.Meta title="产品编号" description={item.pdId} />
                {PD_CATE.map(values => {
                  if (Number(values.itemCode) === item.pdCate) {
                    return <List.Item.Meta title="分类" description={values.pdCateName} />;
                  }
                })}
                <List.Item.Meta
                  title="产品状态"
                  description={
                    <Badge
                      key={item.openFlag}
                      status={item.openFlag === 1 ? 'success' : 'error'}
                      text={
                        <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>
                          {item.openFlag === 1 ? '启用' : '停用'}
                        </span>
                      }
                    />
                  }
                />
                {checkPermissions([
                  'mgr:baseProductInfo:updataPdInfo',
                  'mgr:baseProductInfo:updataPdInfoOpenFlag',
                ]) && (
                  <List.Item.Meta
                    description={
                      <span>
                        <Authorized authority="mgr:baseProductInfo:updataPdInfo" noMatch={null}>
                          <a onClick={() => this.update(item.pdId)}>修改</a>
                          {checkPermissions('mgr:baseProductInfo:updataPdInfoOpenFlag') && (
                            <Divider type="vertical" />
                          )}
                        </Authorized>
                        <Dropdown
                          overlay={
                            <Menu>
                              {checkPermissions('mgr:baseProductInfo:updataPdInfoOpenFlag') && (
                                <Menu.Item
                                  key="look"
                                  onClick={() => this.ableStatus(item.pdId, item.openFlag)}
                                >
                                  {item.openFlag === 1 ? '停用' : '启用'}
                                </Menu.Item>
                              )}
                            </Menu>
                          }
                        >
                          <a style={{ marginLeft: 8 }}>
                            更多 <DownOutlined />
                          </a>
                        </Dropdown>
                      </span>
                    }
                  />
                )}
              </List.Item>
            )}
          />
          <Pagination {...pagination} />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
